{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# categorical_corssentropy\n",
    "\n",
    "$L(y,\\tilde y)= - \\sum y\\log \\tilde y$，由于只有$y_i=1$，简化为$L(y, \\tilde y) = - \\log\\tilde y_i$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras.losses import categorical_crossentropy\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(), dtype=float32, numpy=0.6931472>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_true = tf.constant([1,0],tf.float32)\n",
    "y_pred = tf.constant([0.5,0.5],tf.float32)\n",
    "categorical_crossentropy(y_true, y_pred)\n",
    "# loss = - ln(0.5) = 0.69"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.6931472, 1.2039728], dtype=float32)>"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'''\n",
    "y_true = \n",
    "1 0\n",
    "1 0\n",
    "'''\n",
    "y_true = tf.constant([[1,0],[1,0]],tf.float32)\n",
    "'''\n",
    "y_true = \n",
    "0.5 0.5\n",
    "0.3 0.7\n",
    "'''\n",
    "\n",
    "y_pred = tf.constant([[0.5,0.5],[0.3,0.7]],tf.float32)\n",
    "# 分别对每一行计算loss\n",
    "categorical_crossentropy(y_true, y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(1, 2), dtype=float32, numpy=array([[0.6931472, 1.2039728]], dtype=float32)>"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_true = tf.constant([[[1,0],[1,0]]],tf.float32)\n",
    "y_pred = tf.constant([[[0.5,0.5],[0.3,0.7]]],tf.float32)\n",
    "# 高维情况下，都是只对最后一个维度计算loss，其它维度保持不变\n",
    "categorical_crossentropy(y_true, y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
